package com.xue.mq;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.xue.bean.SeckillMessage;

/**
 * Created by jiangyunxiong on 2018/5/29.
 */
@Service
public class MQReceiver2 {

    private static Logger log = LoggerFactory.getLogger(MQReceiver2.class);

    
    
    /**
     * 	监听mq序列
     * @param message
     */
    @RabbitListener(queues=MQConfig.QUEUE)
    public void receive(String message){
        log.info("receive message:"+message);
        SeckillMessage m = stringToBean(message, SeckillMessage.class);
        String userId = m.getUserId();
        String productId = m.getProductId();
       
//        GoodsVo goodsVo = goodsService.getGoodsVoByGoodsId(goodsId);
//        int stock = goodsVo.getStockCount();
//        if(stock <= 0){
//            return;
//        }
//
//        //判断重复秒杀
//        SeckillOrder order = orderService.getOrderByUserIdGoodsId(user.getId(), goodsId);
//        if(order != null) {
//            return;
//        }
        System.err.println("productId : "+productId);
        System.err.println("userId : "+userId);
        //减库存 下订单 写入秒杀订单
        //seckillService.seckill(user, goodsVo);
        System.err.println("************调用方法****************");
    }

    @RabbitListener(queues = MQConfig.TOPIC_QUEUE1)
    public void receiveTopic1(String message) {
        log.info(" topic  queue1 message:" + message);
    }

    @RabbitListener(queues = MQConfig.TOPIC_QUEUE2)
    public void receiveTopic2(String message) {
        log.info(" topic  queue2 message:" + message);
    }
    
    public static <T> T stringToBean(String str, Class<T> clazz) {
        if (str == null || str.length() <= 0 || clazz == null) {
            return null;
        }
        if (clazz == int.class || clazz == Integer.class) {
            return (T) Integer.valueOf(str);
        } else if (clazz == long.class || clazz == Long.class) {
            return (T) Long.valueOf(str);
        } else if (clazz == String.class) {
            return (T) str;
        } else {
            return JSON.toJavaObject(JSON.parseObject(str), clazz);
        }
    }

}
